package com.demo.cgfpd;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.eclipse.jetty.util.StringUtil;

import cn.ljl.sand.jws.OutSideDataReceiveItf;
import cn.ljl.sand.jws.OutSideDataReceiveItfPortType;

import com.demo.common.model.Cgfpd;
import com.demo.common.model.Cgfpdmp;
import com.demo.common.model.NCFSJL;
import com.demo.common.model.Ncdzb;
import com.demo.general.NcdzbService;
import com.demo.ncfsjl.NCFSJLService;
import com.demo.xhfyd.XhfydService;
import com.jfinal.aop.Inject;
import com.jfinal.plugin.activerecord.Page;

/**
 * 本 demo 仅表达最为粗浅的 jfinal 用法，更为有价值的实用的企业级用法
 * 详见 JFinal 俱乐部: http://jfinal.com/club
 * 
 * NC_FSJLService
 * 所有 sql 与业务逻辑写在 Service 中，不要放在 Model 中，更不
 * 要放在 Controller 中，养成好习惯，有利于大型项目的开发与维护
 */
public class CgfpdService {
	
	@Inject
	XhfydService service;
	@Inject
	NCFSJLService fsjlservice;
	@Inject
	NcdzbService ncdzbService;
	@Inject
	CgfpdmxService mpservice;
	/**
	 * 所有的 dao 对象也放在 Service 中，并且声明为 private，避免 sql 满天飞
	 * sql 只放在业务层，或者放在外部 sql 模板，用模板引擎管理：
	 * 			http://www.jfinal.com/doc/5-13
	 */
	private Cgfpd dao = new Cgfpd().dao();
	
	public Page<Cgfpd> paginate(int pageNumber, int pageSize) {
		return dao.paginate(pageNumber, pageSize, "select *", "from CGFPD order by RQ desc");
	}
	
	public Page<Cgfpd> paginate(int pageNumber, int pageSize,String startDate,String endDate,
			String djbh, String gysdm, String gysmc, String fkfs) {
		StringBuilder sql = new StringBuilder();
		sql.append("from CGFPD fpd join GONGHUOSHANG ghs on fpd.DM1 = ghs.GHSDM")
			.append(" left join NC_FSJL ls on ls.DJBH = fpd.DJBH and RESULT = '1'")
			.append(" where 1 = 1");
		if(StringUtil.isNotBlank(startDate)) {
			sql.append(" AND fpd.RQ>='"+startDate+"'");
		}
		if(StringUtil.isNotBlank(endDate)) {
			sql.append(" AND fpd.RQ<='"+endDate+"'");
		}
		if(StringUtil.isNotBlank(djbh)) {
			sql.append(" AND fpd.DJBH like '%"+djbh+"%'");
		}
		if(StringUtil.isNotBlank(gysdm)) {
			sql.append(" AND ghs.GHSDM like '%"+gysdm+"%'");
		}
		if(StringUtil.isNotBlank(gysmc)) {
			sql.append(" AND ghs.GHSMC like '%"+gysmc+"%'");
		}
		sql.append(" ORDER BY fpd.RQ DESC");
		StringBuilder sql_head = new StringBuilder();
		sql_head.append("select fpd.DJBH,convert(date,fpd.RQ) as RQ,ghs.GHSDM,ghs.GHSMC,convert(int,fpd.SL) as SL,")
			.append("convert(decimal(18,2),fpd.JE) as JE,convert(decimal(18,2),JE*fpd.BYZD13) as SE,")
			.append("convert(decimal(18,2),JE*(1-fpd.BYZD13)) as QSJE,fpd.BZ,")
			.append("case when NCBILLID is not null then '是' end as issend");
		return dao.paginate(pageNumber, pageSize, sql_head.toString(), sql.toString());
	}
	
	public Cgfpd findById(String id) {		
		return dao.findById(id);
	}
	
	public void deleteById(String id) {
		dao.deleteById(id);
	}

	public boolean isXml(String str){
		boolean flag = true;
		try {
			DocumentHelper.parseText(str);
		} catch (Exception e) {
			flag = false;
		}
		return flag;		
	}
	
	public void syncupdate(String para) throws Exception {
		Cgfpd cgfpd = dao.findById(para);
		NCFSJL nf = fsjlservice.findById(para);
		String NCBILLID = "";
		if (nf != null) {
			NCBILLID = nf.getStr("NCBILLID");
		}
		Document doc = makeCgfpdXml(cgfpd, NCBILLID);
		OutSideDataReceiveItf os = new OutSideDataReceiveItf();// NC配置类
		OutSideDataReceiveItfPortType datRecv = os.getOutSideDataReceiveItfSOAP11PortHttp();
		String str = datRecv.receiveXmlData(doc.asXML(), "PAYABLEBILL");
		String result = "0", comment = "";
		if(isXml(str)){
			Document document = DocumentHelper.parseText(str);
			Element ele0 = document.getRootElement();
			Element ele1 = ele0.element("result");
			result = ele1.getTextTrim();
			Element ele2 = ele0.element("comment");
			comment = ele2.getTextTrim();			
		}
		if(comment == ""){
			comment = str;
		}
		fsjlservice.insertNCFSJL(cgfpd.getStr("DJBH"), doc.asXML(), result, str, comment);
	}

	private Document makeCgfpdXml(Cgfpd cgfpd, String NCBILLID) throws Exception {
		List<Cgfpdmp> listMp = mpservice.find(cgfpd.getStr("DJBH"));
		if (listMp.size() == 0) {
			throw new Exception("明细为空！");
		}		
		
		Element root = DocumentHelper.createElement("DataBill");
        Document doucment = DocumentHelper.createDocument(root);
        
        root.addElement("MessageID").addText(cgfpd.getStr("DJBH"));//唯一标识，随机字符
        root.addElement("TargetSystem").addText("OMERP");
        root.addElement("billtype").addText("PAYABLEBILL");
        root.addElement("description").addText(cgfpd.getStr("DJBH"));
        
        Element mainTable = root.addElement("maintable");
        mainTable.addElement("billid").addText(NCBILLID);//单据id，由查询接口返回，新增时此节点值为空，修改时不能为空
        mainTable.addElement("pk_org").addText("01");//NC组织编码
        mainTable.addElement("busi_type").addText("AP01");//NC组织编码
        mainTable.addElement("billdate").addText(cgfpd.getStr("RQ").substring(0, 10));//"2018-11-17"单据日期，注意格式
        mainTable.addElement("oldbillno").addText(cgfpd.getStr("DJBH"));//原单据号->对方系统单据号
        String BZ = cgfpd.getStr("BZ");
        BZ = BZ==null?"":BZ;
        mainTable.addElement("scomment").addText(BZ);//备注
        
        Element bodys = mainTable.addElement("bodys");
        int i = 1;
        for(Cgfpdmp mp:listMp){
        	Element item = bodys.addElement("item");
            item.addElement("itemid").addText(String.valueOf(i));//明细行号
            Ncdzb dzb = ncdzbService.findById(cgfpd.getStr("DM1"));
			if(dzb == null){
				throw new Exception("NC供货商编码为空");
			}
            item.addElement("custsup").addText(dzb.getStr("NCMD"));//供应商编码，取NC供应商接口返回的编码jhfkdBean.getStr("DM1")
            item.addElement("scomment").addText(mp.getStr("BZ")==null?"":mp.getStr("BZ"));//摘要abc211（说明）
            item.addElement("subjcode").addText("14050101");//贷方科目编码
            item.addElement("pk_currtype").addText("CNY");//默认CNY
            item.addElement("rate").addText("1");//汇率，默认为1
            item.addElement("money").addText(mp.getStr("JE"));//借方原币金额
            String se = "";
			if(StringUtil.isNotBlank(mp.getStr("BYZD13"))){
				Double je = Double.valueOf(mp.getStr("JE"));
				Double sl = Double.valueOf(mp.getStr("BYZD13"));
				se = String.valueOf(je*sl);
			}
            item.addElement("taxamount").addText(se);//借方原币金额
            item.addElement("pk_deptid").addText("OM06");//NC部门编码
            item.addElement("contractno").addText("");//合同号
            item.addElement("material").addText(mp.getStr("FLDM"));//NC物料编码
            item.addElement("quantity_cr").addText(mp.getStr("SL"));//借方数量
            item.addElement("busidate").addText(cgfpd.getStr("RQ").substring(0, 10));//起算日期，长度8位
            item.addElement("brands").addText(mp.getStr("NCPP")==null?"":mp.getStr("NCPP"));//品牌，长度8位
            item.addElement("taxrate").addText("");//税率
            i++;
        }
		return doucment;
	}

}
